package com.iyang.bootredis.service.impl;

import com.iyang.bootredis.cache.UserCache;
import com.iyang.bootredis.mapper.UserMapper;
import com.iyang.bootredis.model.User;
import com.iyang.bootredis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: Mu_YI
 * @Date: 2019/3/6 22:59
 * @Version 1.0
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCache userCache;

    @Override
    public boolean saveUser(User user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean updateUserById(User user) {
        return userMapper.updateByPrimaryKey(user) > 0;
    }

    @Override
    public boolean deleteUserById(Long id) {
        return userMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public User selectUserById(Long id) {
        User user =  userCache.selectUserById(id);
        if(user == null){
            user = userMapper.selectByPrimaryKey(id);
        }
        userCache.saveUser(user);

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> selectUser(String name, int pageNumber, int pageSize, boolean paging) {
        List<User> userList = userMapper.selectUser(name, pageNumber, pageSize, false);
        List<User> selectUser = userMapper.selectUser(name, pageNumber, pageSize, paging);
        Map<String,Object> resultMap = new HashMap<>();
        if(paging){
            resultMap.put("totalCount",userList.size());
            resultMap.put("totalPage",Math.ceil(userList.size()*1.0/pageSize));
        }
        resultMap.put("entries",selectUser);
        return resultMap;
    }

    public static void main(String[] args) {
        // SQL
        System.out.println("123".hashCode());
        System.out.println("王五转给李四100,王五减去100");
        Map<String,Object> resultMap = new HashMap<>();
        // key  123  789
        int a = 10/0;
        // 开启事务了的话


        AtomicInteger integer = new AtomicInteger();
        integer.getAndIncrement();





        //SQL
        System.out.println("李四应该加100快");
    }
}
